<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>图片上传</title>
</head>

<body>
<!-- 要将父布局的position设置为relative，父布局将无法包裹input -->
<div style="position: relative;">
    <!--设置input的position为absolute，使其不按文档流排版，并设置其包裹整个布局 -->
    <!-- 设置opactity为0，使input变透明 -->
    <!-- 只接受jpg，gif和png格式 -->
    <input id="upload-input" style="position: absolute; top: 0; bottom: 0; left: 0;right: 0; opacity: 0;" type="file" accept="image/gif, image/jpg, image/png" onchange="showImg(this)" multiple />
    <!-- 自定义按钮效果 -->
    <div style="text-align: top">
        <span style="font-size: 12px;">上传文件：</span>
        <img id="upload" src="./upload.png" style="width: 40px; height: 40px; vertical-align: middle;" />
    </div>
</div>
<div id="imgContainer" style="margin-top: 10px;"></div>
<input type="button" onclick="postData();" value="下一步" name="" style="width:100px;height:30px;">

</body>
<script type="text/javascript">
    function showImg(obj) {
        var files = obj.files
        // document.getElementById("imgContainer").innerHTML = getImgsByUrl(files)
        getImgsByFileReader(document.getElementById("imgContainer"), files)
    }

    // 使用window.URL.createObjectURL(file)读取file实例并显示图片
    function getImgsByUrl(files) {
        var elements = ''
        for (var i = 0; i < files.length; i++) {
            var url = window.URL.createObjectURL(files[i])
            elements += "<img src='"+ url + "' style='width: 40px; height: 40px; vertical-align: middle; margin-right: 5px;' />"
        }
        return elements
    }

    // 使用FileReader读取file实例并显示图片
    function getImgsByFileReader(el, files) {
        for (var i = 0; i < files.length; i++) {
            let img = document.createElement('img')
            img.setAttribute('style', 'width: 400px; height: 400px; vertical-align: middle; margin-right: 5px;')
            el.appendChild(img)
            var reader = new FileReader()
            reader.onload = function(e) {
                img.src = e.target.result
            }
            reader.readAsDataURL(files[i])
        }
    }
    function postData(){
        var formData = new FormData();
        formData.append("image",$("#imgContainer")[0].children[0].files[0]);
        // formData.append("service",'App.Passion.UploadFile');
        // formData.append("token",token);
        $.ajax({
            url:'upload/', /*接口域名地址*/
            type:'post',
            data: formData,
            contentType: false,
            processData: false,
            success:function(res){
                console.log(res.data);
                // if(res.data["code"]=="succ"){
                //     alert('成功');
                // }else if(res.data["code"]=="err"){
                //     alert('失败');
                // }else{
                //     console.log(res);
                // }
            }
        })
    }
</script>
</html>